/**
 * 微信 主应用入口
 *
 */
define(["echarts", "public/app.min"], function (echarts) {

    var self,
        app = win.app,
        types = [],
        units = [],//单位
        zhiwei = [],//职位
        juese = [],//角色
        menus = [],
        others = {
            hasgwc: true
        },
        statsSJ = {
            A: 0, B: 0, C: 0
        },
        keyword,
        sData={
            keyword:''
        },
        page = {
            current: 1,
            totalNum: 0,
            taskList: [],
            count: {
                PGCOUNT: 0,
                BGCOUNT: 0,
                HFCOUNT: 0
            },
            lbcount: 3
        }
    ;

    function getUserInfoBack() {

        menus.pushArray(app.userInfos.auths, true);

        menus.iFilter({
            o: {
                permission_: 'wx0006'
            },
            cb: function (arr, i) {
                if (i > 0) {
                    others.hasgwc = true;
                }
            }
        });
    }

    app.newModule({
        init: function () {
            self = this;

            self._super({
                _tag: 'p_after_sale',
                _search: {
                    data:sData,
                    methods: {
                        clickIn: function() {
                            var getFirst = document.getElementsByClassName('noneFouce')[0];
                            var getLast = document.getElementsByClassName('hasFouce')[0];
                            getFirst.style.display = 'none';
                            getLast.style.display = 'block';
                            getLast.focus();


                        },
                        lostIn: function(e) {
                            //console.log(e,sData.keyword)
                            var getFirst = document.getElementsByClassName('noneFouce')[0];
                            var getLast = document.getElementsByClassName('hasFouce')[0];

                            if(sData.keyword == '') {
                                getFirst.style.display = 'block';
                                getLast.style.display = 'none';
                            }

                        },
                        scanQRCode: function () {
                            app.scanQRCode(function (code) {
                                self.openXcqd(code)
                            })
                        },
                    }
                },
                _readyBefore: function () {
                    //最先执行
                    self.mData = {
                        authData: [],
                        obj: {
                            dqs: 0,
                            wfh: 0
                        }
                    };

                    app.mainPage = {};

                    // 用户数据 放到main对象里面  废弃
                    self.userInfo = {
                        ID: app.cookie('_WX_ACCOUNT_'),
                        NAME: app.cookie('_WX_USERNAME_'),
                        MOBILE: app.cookie('_WX_MOBILE_'),
                        SID: app.cookie('_WX_ID_'),
                        ORGID: app.cookie('_WX_ORGID_'),
                    };

                    self.zhiwei = zhiwei;//职位
                    self.juese = juese;//角色

                }
            }, win);

        },
        _search: function (data) {

            keyword = data.keyword.trim();
            self.openXcqd(keyword);

        },
        setLocation: function () {
            let latlng = app.wxLocationCache();
            if (latlng.lat) {
                app.lnglatConvert({
                    lat: latlng.lat,// 纬度
                    lng: latlng.lng,// 经度
                    cb: function (lnglat) {
                        app.ajax({
                            xurl: "api/wx/gwa/setLocation",
                            xdata: {
                                GWAA020: lnglat.lat,// 纬度
                                GWAA019: lnglat.lng// 经度
                            }
                        });
                    }
                });
            }
        },
        getZhiwei: function () {
            app.ajax({
                xurl: "api/wx/gwa/getZw",
                cb: function (result) {
                    if (result.ok) {
                        var data = result.data;
                        zhiwei.pushArray(data.data, true);
                    }
                }
            });
        },
        getJuese: function () {
            app.ajax({
                xurl: "api/wx/gwa/getJs",
                cb: function (result) {
                    if (result.ok) {
                        var data = result.data;
                        juese.pushArray(data.data, true);
                    }
                }
            });
        },
        getUnits: function () {
            app.ajax({
                xurl: "api/wx/gwa/getGwablList",
                ocache: true,
                xtime: '1d',
                cb: function (result) {
                    if (result.ok) {
                        // units.pushArrlostInay(result.data.data);
                        units.pushArray(result.data.data);
                    }
                }
            });
        },
        getType: function () {
            app.ajax({
                xurl: "api/wx/gwat100/getGwahData",
                cb: function (result) {
                    if (result.ok) {
                        types.pushArray(result.data.data);
                    }
                }
            });
        },
        dataDrawing: function () {

            //执行数据渲染
            new Vue({
                el: '#content',
                data: {
                    others: others,
                    menus: menus,
                    items: types,
                    statsSJ: statsSJ,
                    page: page
                },
                methods: {
                    go: function (v) {
                        app.openPage({
                            src: "xcqd/scene.html",
                            argsKey: 'scene_page',
                            args: {
                                obj: v,
                                cb: function () {
                                }
                            }
                        });
                    },
                    openFL: function () {
                        app.openPage({
                            src: "gwcxd/classes.html"
                        });
                    },
                    open: function (type) {
                        if (type == 'A') {
                            app.openPage({
                                src: 'fwpg/fwpg.html',
                                args: {}
                            });
                        } else if (type == 'B') {
                            app.openPage({
                                src: 'fwbg/fwbg.html',
                                args: {}
                            });
                        } else if (type == 'C') {
                            app.openPage({
                                src: 'fwhf/fwhf.html',
                                args: {}
                            });
                        }
                    }
                },
                updated: function () {
                    mui(".mui-slider").slider({
                        interval: 3000
                    });
                }
            });

        },
        initFilters: function () {
            // 声明全局过滤器
            Vue.filter('MMRD001STATUS', function (t) {
                return win.eval({'1': '安装', '2': '维修', '3': '保养'})[t];
            });

            Vue.filter('MMRD019STATUS', function (t) {
                return win.eval({'1': '紧急', '2': '一般'})[t];
            });

            Vue.filter('sexStatus', function (t) {
                return win.eval({'0': '未知', '1': '男', '2': '女'})[t];
            });

            Vue.filter('MMRD020STATUS', function (t) {
                return win.eval({'1': '发起', '2': '受理', '3': '派工', '4': '报工', '5': '评价', '6': '回访结案'})[t];
            });

            Vue.filter('GWBJ005STATUS', function (t) {
                return win.eval({'1': '主要对手', '2': '重要对手', '3': '一般对手', '4': '其他对手'})[t];
            });

            Vue.filter('goodsUnits', function (t) {
                var a = units.filterKV({'GWABL001': t});
                if (a.length > 0) {
                    return a[0].GWABL003;
                } else {
                    return '未知';
                }
            });

            Vue.filter('zhiwei', function (t) {
                var a = zhiwei.filterKV({'GWBD001': t});
                if (a.length > 0) {
                    return a[0].GWBDL003;
                } else {
                    return '未知';
                }
            });

            Vue.filter('juese', function (t) {
                var a = juese.filterKV({'GWAW001': t});
                if (a.length > 0) {
                    return a[0].GWAWL003;
                } else {
                    return '未知';
                }
            });

            Vue.filter('goodsImgsUtils', function (name) {
                if (name) {
                    var origin = location.origin;

                    if (origin.indexOf('localhost') == -1) {
                        return location.origin + '/wissun-smfile/' + name.split(",")[0];
                    } else {
                        return 'http://fx.digiwin.com:9017/wissun-smfile/' + name.split(",")[0];
                    }
                } else {
                    return '../../../img/wx/images.png';
                }
            });

            Vue.filter('orderImgsUtils', function (name) {
                if (name) {
                    if (name.indexOf('wx-uploads') != -1) {
                        return app.cxt() + name;
                    } else {
                        // return app.cxt() + 'wx-uploads/imgs/' + name;
                        return "E:\\projs\\mingyi\\crm6.0\\crm-wissun-upload\\" + name;
                    }
                } else {
                    return '../../static/img/images.png';
                }
            });

            Vue.filter('dateFmt', function (date) {
                if (date) {
                    return date.replace(" 00:00:00", "")
                }
                return ""
            });
        },
        openXcqd: function (code) {

            app.openPage({
                src: "common/selectSearchPage.html",
                args: {
                    url: 'api/wx/aftersale/getTodayTask',
                    keyword: code,
                    nodata: '无服务单',
                    keyArray: ['MMRF001', 'GWAKL004'],
                    cb: function (res) {
                        app.openPage({
                            src: "xcqd/scene.html",
                            argsKey: 'scene_page',
                            args: {
                                obj: app.cloneJSON(res),
                                cb: function () {
                                }
                            }
                        });
                    }
                }
            });
        },
        getTodayTask: function () {
            app.ajax({
                xurl: 'api/wx/aftersale/getTodayTask',
                xdata: {},
                cb: function (result) {
                    if (result.ok) {
                        var data = result.data.data;
                        data.forEach(function (item, index) {
                            var d = item.MMRFTIME.split(':');
                            if (d != undefined) {
                                item.MMRFTIME = d[0] + ':' + d[1]
                            }

                            if (item.MMRD020 == '3') {
                                item.status = false;
                            } else {
                                item.status = true;
                            }

                        });
                        page.taskList = data;
                    }
                }
            })
        },
        formPie: function () {

            app.ajax({
                xurl: 'api/wx/aftersale/getMMRK',
                xdata: {},
                cb: function (res) {
                    if (res.ok) {
                        var data = res.data.data;
                        var chartDiv = doc.getElementById('mydDiv');
                        // var count = data.length + page.lbcount;
                        //动态增加的图表改为只生成一个图表
                        var count = 1 + page.lbcount;

                        var indicator = doc.getElementById('indicator');
                        for (var i = 0; i < count; i++) {
                            let div = doc.createElement('div');
                            if (i == 0)
                                div.setAttribute("class", "mui-indicator mui-active");
                            else
                                div.setAttribute("class", "mui-indicator");

                            indicator.appendChild(div)
                        }

                        //给页面添加标签
                        // data.forEach(function (d, index) {
                        //     var id = "MMRK" + index;
                        //     if (index == 0)
                        //         chartDiv.innerHTML += ('<div class="echartBox">\n' +
                        //             '            <div id="' + id + '" style="height: 100%;width: 100%"></div>\n' +
                        //             '        </div>');
                        //     else {
                        //         var loopdiv = document.getElementById('loopDiv');
                        //         var gzdiv = document.getElementById('gzdiv');
                        //
                        //         let div = document.createElement('div');
                        //         div.setAttribute("class", "mui-slider-item");
                        //         var ele = "<h5>满意度图表</h5>";
                        //         ele += ('<div class="echartBox">\n' +
                        //             '            <div id="' + id + '" style="height: 100%;width: 100%"></div>\n' +
                        //             '        </div>');
                        //
                        //         div.innerHTML = ele;
                        //         loopdiv.insertBefore(div, gzdiv)
                        //     }
                        // });


                        var id = "MMRK0";
                        chartDiv.innerHTML += ('<div class="echartBox">\n' +
                            '            <div id="' + id + '" style="height: 100%;width: 100%"></div>\n' +
                            '        </div>');
                        // var loopdiv = document.getElementById('loopDiv');
                        // var gzdiv = document.getElementById('gzdiv');

                        let div = document.createElement('div');
                        div.setAttribute("class", "mui-slider-item");
                        // var ele = "<h5>满意度图表</h5>";
                        // ele += ('<div class="echartBox">\n' +
                        //     '            <div id="' + id + '" style="height: 100%;width: 100%"></div>\n' +
                        //     '        </div>');
                        //
                        // div.innerHTML = ele;
                        // loopdiv.insertBefore(div, gzdiv);

                        //统一生成chart
                        // data.forEach(function (d, index) {
                        //     var id = "MMRK" + index;
                        //     var pieData = [];
                        //     if (d.list.length > 0) {
                        //         d.list.forEach(function (item, index1) {
                        //             pieData.push({
                        //                 name: '第' + (index1 + 1) + '颗星',
                        //                 value: item.MMRK004_SUM
                        //             })
                        //         })
                        //     }
                        //     formMMRKPie(id, pieData);
                        // });
                        var pieData = [];
                        data.forEach(function (d, index) {
                            if (d.list.length > 0) {
                                var count = 0;
                                d.list.forEach(function (item, index1) {
                                    //比如此时5颗星评价有有一个 就是1*5
                                    count += (item.MMRK004_SUM * (index1+1));
                                });
                                pieData.push({
                                    name: d.MMRJL004,
                                    value: count
                                })
                            }
                        });

                        formMMRKPie(id, pieData);

                        function formMMRKPie(id, pieData) {
                            var pie3 = echarts.init(doc.getElementById(id));
                            pie3.setOption({
                                series: [
                                    {
                                        type: 'pie',
                                        // 第一个参数是内圆半径，第二个参数是外圆半径，相对饼图的宿主div大小
                                        radius: ['40%', '50%'],
                                        avoidLabelOverlap: true,
                                        // 禁用饼状图悬浮动画效果
                                        animation: true,
                                        label: {
                                            normal: {
                                                // 这里的竖线前面的b 和 per是相应参数的别名(我理解为别名)，对应下面rich属性里的b和per
                                                formatter: '{b|{b}：}{c} ({per|{d}%})',
                                                backgroundColor: '#eee',
                                                borderColor: '#aaa',
                                                borderWidth: 1,
                                                padding: 5,
                                                borderRadius: 4,
                                                rich: {
                                                    b: {
                                                        fontSize: 8,
                                                        lineHeight: 15
                                                    },
                                                    per: {
                                                        align: 'center'
                                                    }
                                                }
                                            }
                                        },
                                        data: pieData
                                    }
                                ]
                            })
                        }

                    }
                }
            });

            var d = new Date();
            app.ajax({
                xurl: "api/wx/aftersale/getEchartData",
                xdata: {
                    DATE_START: d.getFullYear() + "-01-01",
                    DATE_END: d.getFullYear() + "-12-31",
                    YEAR: d.getFullYear()
                },
                cb: function (res) {
                    if (res.ok) {
                        var data = res.data.data;
                        var names1 = [];
                        var datas1 = [];

                        if (data.pieData1.length > 0) {
                            data.pieData1.forEach(function (d, index) {
                                names1.push(d.GWAML003);
                                datas1.push({value: d.COUNT, name: d.GWAML003});
                            });
                        }

                        var names2 = [];
                        var datas2 = [];

                        if (data.pieData2.length > 0)
                            data.pieData2.forEach(function (d, index) {
                                names2.push(d.MMRL003);
                                datas2.push({value: d.COUNT, name: d.MMRL003});
                            })

                        var names = [];
                        var pecents = [];
                        if (data.lineData.length > 0) {
                            var arr = [];
                            var arrStr = '';
                            data.lineData.forEach(function (d, index) {
                                arr.push(d.NAME);
                                arrStr += (d.NAME + '|');
                            })

                            var newArr = [];
                            arr.forEach(function (a, index) {
                                if (arrStr.indexOf(a) != -1) {
                                    var count = getCount(arrStr, a, 0);
                                    newArr.push({
                                        NAME: arr.filter(child => (child == a))[0],
                                        count: count
                                    });
                                    arrStr = arrStr.replaceAll(a, "");
                                }
                            });
                            newArr.forEach(function (narr, index) {

                                data.lineData.iFilter({
                                    o: {
                                        NAME: narr.NAME
                                    },
                                    cb: function (datas, i) {
                                        if (i > 0) {
                                            var percents = 0.0;
                                            datas.forEach(function (d, index) {
                                                // percents += ((d.MMRGDOCNO_SUM == 0 ? 0 : d.serverTime.div(d.MMRGDOCNO_SUM) * 100).toFixed(2));
                                                percents = percents.add((d.MMRGDOCNO_SUM == 0 ? 0 : d.serverTime.div(d.MMRGDOCNO_SUM)).toFixed(2));
                                            });

                                            names.push(datas[0].NAME+"("+percents+"小时/"+i+"单)");
                                            pecents.push(percents.div(i).toFixed(2));
                                        }
                                    }
                                });
                            });
                        }

                        self.buildPie("pieChart1", names1, datas1);
                        self.buildPie("pieChart2", names2, datas2);
                        self.buildPie("pieChart2_duplicate", names2, datas2);
                        self.buildBar(names, pecents);

                        function getCount(targetStr, param, count) {
                            if (!count) {
                                count = 0;
                            }

                            if (targetStr.indexOf(param) != -1) {
                                count++;
                                targetStr = targetStr.replace(param, "");
                                return getCount(targetStr, param, count);
                            } else {
                                return count;
                            }
                        }

                    }
                }
            });
        },
        buildPie: function (pieId, names, pieData) {
            var pie1 = echarts.init(doc.getElementById(pieId));
            pie1.setOption({

                backgroundColor: '#fff',
                legend: {
                    bottom: 10,
                    left: 'center',
                    data: names
                },
                grid: {
                    top: 10,
                    bottom: 30,
                    containLabel: true//这常用于『防止标签溢出』的场景
                },
                calculable: true,
                series: [
                    {
                        type: 'pie',
                        radius: '65%',
                        center: ['50%', '38%'],
                        selectedMode: 'single',
                        label: {
                            normal: {
                                position: 'inner'
                            }
                        },
                        labelLine: {
                            normal: {
                                show: false
                            }
                        },
                        data: pieData
                    }
                ]
            });
        },
        buildBar: function (names, percents) {
            var getOption = function () {
                var chartOption = {
                    legend: {
                        data: ['负荷时间']
                    },
                    grid: {
                        x: 35,
                        x2: 10,
                        y: 30,
                        y2: 25
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            mark: {
                                show: true
                            },
                            dataView: {
                                show: true,
                                readOnly: false
                            },
                            magicType: {
                                show: true,
                                type: ['bar']
                            },
                            restore: {
                                show: true
                            },
                            saveAsImage: {
                                show: true
                            }
                        }
                    },
                    calculable: false,
                    xAxis: [{
                        type: 'category',
                        data: names
                    }],
                    yAxis: [{
                        type: 'value',
                        data: percents,
                        splitArea: {
                            show: true
                        }
                    }],
                    series: [{
                        name: '负荷时间',
                        type: 'bar',
                        data: percents
                    }]
                };
                return chartOption;
            };

            var byId = function (id) {
                return document.getElementById(id);
            };
            var barChart = echarts.init(byId('barChart'));
            barChart.setOption(getOption());

            var barChart_duplicate = echarts.init(byId('barChart_duplicate'));
            barChart_duplicate.setOption(getOption());
        },
        getNum: function () {
            app.ajax({
                xurl: 'api/wx/aftersale/getNum',
                cb: function (res) {
                    if (res.ok) {
                        var counts = res.data.data;
                        page.count = {
                            PGCOUNT: counts[0].COUNT,
                            BGCOUNT: counts[1].COUNT,
                            HFCOUNT: counts[2].COUNT
                        };

                    }
                }
            })
        },
        _ready: function () {
            self.dataDrawing();

            if (app.userInfos) {
                getUserInfoBack();
            } else {
                app.getUserInfoBack = function () {
                    getUserInfoBack();
                };
            }

            self.formPie();
            self.getTodayTask();
            self.getNum();

        },
        _lazy: function () {
            this._super();

            self.initFilters();

            new Vue({
                el: '#foot',
                data: {
                    keyword: keyword
                },
                methods: {
                    openFoot: function (t) {
                        if (t == 'pg') {
                            app.openPage({
                                src: "fwpg/fwpg.html"
                            });
                        } else if (t == 'bg') {
                            app.openPage({
                                src: "fwbg/fwbg.html",

                            });
                        } else if (t == 'wo') {
                            app.openPage({
                                src: "me/me.html",
                                args: {
                                    auths: menus
                                }
                            });
                        }
                    }

                }
            });

            app.getImgUrl = function () {
                var origin = location.origin;
                if (origin.indexOf('localhost') == -1) {
                    return location.origin + '/wissun-smfile/';
                } else {
                    return 'http://fx.digiwin.com:9017/wissun-smfile/';
                }
            };

            self.getUnits();
            self.getJuese();
            self.getZhiwei();

            self.getType();

            app.filterRepeat = function (arr) {
                var arrStr = '';
                arr.forEach(function (d, index) {
                    arr.push(d);
                    arrStr += (d + '|');
                })

                var newArr = [];
                arr.forEach(function (a, index) {
                    if (arrStr.indexOf(a) != -1) {
                        newArr.push(arr.filter(child => (child == a))[0]);
                        arrStr = arrStr.replaceAll(a, "");
                    }
                });
                return newArr;

                //或者
                // return arr.filter((currValue, currIndex,self)=>self.indexOf(currValue)===currIndex);
            }


            // var arr = [1, 2, 2, 3, 4, 5, 5, 6, 7, 7,8,8,0,8,6,3,4,56,2];
            // var arr2 = arr.filter((x, index,self)=>self.indexOf(x)===index)
            // console.log(arr2);

        }
    });

});